import React, { useState } from 'react';
import { Menu, Button, Modal, Tooltip, Dropdown, ConfigProvider } from 'antd';
import { 
  AppstoreOutlined, 
  BuildOutlined, 
  DatabaseOutlined,
  ExportOutlined,
  SaveOutlined,
  EyeOutlined,
  SettingOutlined,
  PlusOutlined,
  MenuOutlined
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import ComponentPalette from './components/ComponentPalette';
import Canvas from './components/Canvas';
import PropertyPanel from './components/PropertyPanel';
import ModelEditor from './components/ModelEditor';
import { exportProject } from './utils/codeGenerator';
import { useStore } from './store/useStore';
import TemplateSelector from './components/TemplateSelector';
import { PageType, LayoutType } from './types';
import './App.css';

// 主题配置
const themeConfig = {
  token: {
    colorPrimary: '#1890ff',
    borderRadius: 4,
    colorBgContainer: '#ffffff',
  },
  components: {
    Button: {
      colorPrimary: '#1890ff',
    }
  }
};

// 删除未使用的 PagesRecord 类型

const AppContent: React.FC = () => {
  const [activeMenu, setActiveMenu] = useState<string>('design');
  const [templateModalVisible, setTemplateModalVisible] = useState<boolean>(false);
  
  // 从store中获取状态和方法
  const addPage = useStore(state => state.addPage);
  const pages = useStore(state => state.app.data.pages);
  const currentPageId = useStore(state => state.app.data.currentPageId);
  const setCurrentPage = useStore(state => state.setCurrentPageId);
  
  // 添加新页面
  const handleAddPage = () => {
    const pageId = `page_${Date.now()}`;
    addPage({
      id: pageId,
      name: `页面${Object.keys(pages).length + 1}`,
      path: `/${pageId}`,
      type: PageType.NORMAL,
      layoutType: LayoutType.GRID,
      components: []
    });
    setCurrentPage(pageId);
  };

  // 导出项目
  const handleExport = () => {
    Modal.confirm({
      title: '导出项目',
      content: '确定要导出当前项目吗？',
      okText: '导出',
      cancelText: '取消',
      onOk: () => exportProject('毕业设计'),
    });
  };

  // 预览项目
  const handlePreview = () => {
    Modal.info({
      title: '项目预览',
      content: '预览功能正在开发中...',
      okText: '关闭'
    });
  };

  // 页面下拉菜单项
  const pageMenuItems: MenuProps['items'] = Object.entries(pages).map(([id, page]) => ({
    key: id,
    label: page.name || `页面${id}`,
    onClick: () => setCurrentPage(id)
  }));

  // 当前页面名称
  const currentPageName = currentPageId && pages[currentPageId] 
    ? pages[currentPageId].name 
    : '未选择页面';

  return (
    <div className="app-container">
      {/* 顶部导航栏 */}
      <div className="app-header">
        <div className="app-logo">yong1低代码垂直开发平台</div>
        
        <Menu
          mode="horizontal"
          selectedKeys={[activeMenu]}
          onSelect={({ key }) => setActiveMenu(key as string)}
          style={{ flex: 1 }}
          items={[
            {
              key: 'design',
              label: '设计',
              icon: <BuildOutlined />
            },
            {
              key: 'model',
              label: '数据模型',
              icon: <DatabaseOutlined />
            },
            {
              key: 'templates',
              label: '模板',
              icon: <AppstoreOutlined />
            }
          ]}
        />
        
        <div className="toolbar-group">
          <Tooltip title="保存项目">
            <Button icon={<SaveOutlined />} />
          </Tooltip>
          
          <Tooltip title="预览项目">
            <Button icon={<EyeOutlined />} onClick={handlePreview} />
          </Tooltip>
          
          <Button 
            type="primary" 
            icon={<ExportOutlined />} 
            onClick={handleExport}
          >
            导出项目
          </Button>
        </div>
      </div>
      
      {/* 主内容区 */}
      <div className="app-main">
        {activeMenu === 'design' && (
          <>
            {/* 左侧组件面板 */}
            <div className="sidebar">
              <div className="sidebar-header">组件库</div>
              <div className="sidebar-content">
                <ComponentPalette />
              </div>
            </div>
            
            {/* 中间画布区域 */}
            <div className="main-content">
              <div className="toolbar">
                <div className="toolbar-group">
                  <Dropdown menu={{ items: pageMenuItems }} placement="bottomLeft">
                    <Button icon={<MenuOutlined />}>
                      {currentPageName}
                    </Button>
                  </Dropdown>
                  
                  <Button 
                    type="text" 
                    icon={<PlusOutlined />} 
                    onClick={handleAddPage}
                  >
                    添加页面
                  </Button>
                </div>
                
                <div className="toolbar-group">
                  <Button icon={<SettingOutlined />}>页面设置</Button>
                </div>
              </div>
              
              <div className="canvas-container">
                <Canvas />
              </div>
            </div>
            
            {/* 右侧属性面板 */}
            <div className="property-panel">
              <div className="property-panel-header">属性设置</div>
              <div className="property-panel-content">
                <PropertyPanel />
              </div>
            </div>
          </>
        )}
        
        {activeMenu === 'model' && (
          <div className="main-content">
            <div className="toolbar">
              <div className="toolbar-group">
                <Button type="primary" icon={<PlusOutlined />}>添加模型</Button>
              </div>
            </div>
            <div className="canvas-container">
              <ModelEditor />
            </div>
          </div>
        )}
        
        {activeMenu === 'templates' && (
          <div className="main-content">
            <div className="toolbar">
              <div className="toolbar-group">
                <Button type="primary" icon={<PlusOutlined />}>创建模板</Button>
              </div>
            </div>
            <div className="canvas-container">
              <TemplateSelector onSelect={() => setTemplateModalVisible(false)} />
            </div>
          </div>
        )}
      </div>
      
      <Modal
        title="选择模板"
        open={templateModalVisible}
        onCancel={() => setTemplateModalVisible(false)}
        footer={null}
        width={800}
      >
        <TemplateSelector onSelect={() => setTemplateModalVisible(false)} />
      </Modal>
    </div>
  );
};

const App: React.FC = () => {
  return (
    <ConfigProvider theme={themeConfig}>
      <DndProvider backend={HTML5Backend}>
        <AppContent />
      </DndProvider>
    </ConfigProvider>
  );
};

export default App;